package com.example.administrator.android2019.Note;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.SimpleFormatter;

/**
 *   1.必须重写的方法
 *    构造方法（建库）。onCreate(建表语句）
 * */
public class NoteSqlLiteHelper extends SQLiteOpenHelper {
    private  SQLiteDatabase db;
    public NoteSqlLiteHelper(Context context) {
        super(context, "note.db", null, 1);
        db=getWritableDatabase();
    }
/**
 * 执行一次
 * 创建表（表中的字段跟实体类中的属性一一对应）
 *
 * */
    @Override
    public void onCreate(SQLiteDatabase db) {
       String sql="create table note(id integer primary key autoincrement ,content text,time text)";
       db.execSQL(sql);
    }
/**
 *
 *
 * */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
    public String getTime(){
        Date date=new Date(System.currentTimeMillis());
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyy年MM月dd日 hh:mm:ss");

        return simpleDateFormat.format(date);
    }
    /**
     *  保存数据，将记录保存在SQLite
     * */
    public boolean insertDate(String content ,String time){
       /** String sql="insert into  note(content ,time) values(?,?)";
        db.execSQL(sql,new Object[]{content,time});
        return true;*/
        ContentValues cv=new ContentValues();
        cv.put("content",content);
        cv.put("time",time);
        return db.insert("note",null,cv)>0;
    }
    public boolean deleteDate(int id){
      return   db.delete("note","id=?",new String[]{id+""})>0;

    }
    public boolean updateDate(int id,String content,String time){
        ContentValues cv=new ContentValues();
        cv.put("content",content);
        cv.put("time",time);
        return db.update("note",cv,"id=?",new String[]{id+""})>0;
    }
    public ArrayList<NoteBean> query(){
        ArrayList<NoteBean> list=new ArrayList<NoteBean>();
        String sql="select * from note order by time desc";

        Cursor cursor=db.rawQuery(sql,null);
        while (cursor.moveToNext()){
            int id=cursor.getInt(cursor.getColumnIndex("id"));
            String content=cursor.getString(cursor.getColumnIndex("content"));
            String time=cursor.getString(cursor.getColumnIndex("time"));

            NoteBean noteBean=new NoteBean(id,content,time);
            list.add(noteBean);
        }
       cursor.close();
        return list;
    }

}
